﻿using FtpFileBackup_Oracle.LogHelper;
using FtpFileBackup_Oracle.DbHelper;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FtpFileBackup_Oracle.DataBaseBackup.SqlServer
{
    public class SqlServerBackup : IDataBaseBackup
    {
        private static readonly Dictionary<string, string> DbNameDic = new Dictionary<string, string>();
        public SqlServerBackup()
        {
            SetDbNameList();
        }

        public void Excute()
        {
            foreach (var item in DbNameDic)
            {
                string baseBackupPath = ConfigurationManager.AppSettings["serverSaveBasePath"];
                string dbName = item.Key;
                string currentBackupPath = baseBackupPath + dbName + "\\";
                string date = DateTime.Now.ToString("yyyyMMdd");

                if (!Directory.Exists(currentBackupPath))
                {
                    Directory.CreateDirectory(currentBackupPath);
                }

                var sqlserverDb = new SqlServerDb(item.Value);

                sqlserverDb.OpenConn();

                var sql = string.Format(@"declare @name varchar(250) 
set @name='{0}Backup_{2}.bak'
 
BACKUP DATABASE [{1}] TO  
DISK=@name 
WITH NOFORMAT, NOINIT,  
NAME = N'{1}-完整 数据库 备份', 
SKIP, NOREWIND, NOUNLOAD", currentBackupPath, dbName, date);

                log4netHelper.Info($"使用sql：{sql}进行数据库：{item.Key}的备份");

                sqlserverDb.ExecuteNonQuery(sql);

                sqlserverDb.CloseConn();

                log4netHelper.Info($"完成数据库：{item.Key}的备份");

                FileCompress(new string[] { $"{currentBackupPath}Backup_{date}.bak" });

                DeleteSourceFile(new string[] { $"{currentBackupPath}Backup_{date}.bak" });

                log4netHelper.Info($"完成数据库：{item.Key}的备份文件压缩");
            }
        }

        private void SetDbNameList()
        {
            foreach (ConnectionStringSettings setting in ConfigurationManager.ConnectionStrings)
            {
                if (!string.IsNullOrWhiteSpace(setting.ConnectionString))
                {
                    var configItems = setting.ConnectionString.Split(new string[] { ";" }, StringSplitOptions.RemoveEmptyEntries).ToList();

                    foreach (string item in configItems)
                    {
                        if (item.Contains("=") && (item.ToLowerInvariant().Contains("initial catalog") || item.ToLowerInvariant().Contains("database")))
                        {
                            string[] kv = item.Split(new string[] { "=" }, StringSplitOptions.RemoveEmptyEntries).ToArray();

                            DbNameDic.Add(kv[1].Trim(), setting.ConnectionString.Trim());

                            break;
                        }
                    }
                }
            }

        }

        private void FileCompress(string[] paths)
        {
            foreach (string path in paths)
            {
                SevenZipTool.Compress(path, path.Replace(".bak", ".7z"));
            }
        }

        private void DeleteSourceFile(string[] paths)
        {
            foreach (string path in paths)
            {
                File.Delete(path);
            }
        }
    }
}
